package com.rp.system.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rp.common.utils.RpUtil;
import com.rp.log.annotation.RpLog;
import com.rp.system.dao.RpMessageDao;
import com.rp.system.dao.UserDao;
import com.rp.system.dao.UserMessageDao;
import com.rp.system.po.RpMessage;
import com.rp.system.po.UserMessage;

@Service
@Transactional
public class RpMessageService {

	@Autowired
	private RpMessageDao msgDao;
	
	@Autowired
	private UserMessageDao umDao;
	
	@Autowired
	private UserDao userDao;
	
	/**
	 * 发送消息
	 * @param userIds 接收站ID串，每个ID之间用,分隔
	 * @param message 消息主体
	 * @throws Exception 
	 */
	@RpLog(desc="发送消息")
	public void sendMessage(String userIds, RpMessage message) throws Exception{
		
		if(RpUtil.isNullOrEmpty(userIds)){
			throw new Exception("没有指定消息的接收人");
		}
		
		message.setCreateDate(RpUtil.getCurrentDatetime());
		String messageId = (String) msgDao.save(message);
		
		String[] userIdArr = userIds.split(",");
		for (String userId : userIdArr) {
			
			UserMessage um = new UserMessage();
			um.setUserId(userId);
			um.setMessageId(messageId);
			um.setMarkRead("0");
			um.setCreateDate(RpUtil.getCurrentDatetime());
			umDao.save(um);
		}
		
	}
	
	@RpLog(desc="删除消息")
	public void deleteMessage(String messageId){
		
		msgDao.delete(messageId);
		List<UserMessage> ums = umDao.find("from UserMessage where messageId = ?", messageId);
		for (UserMessage um : ums) {
			umDao.delete(um);
		}
		
	}
	
	
	
	public RpMessageDao getMsgDao() {
		return msgDao;
	}
	
	public UserMessageDao getUmDao() {
		return umDao;
	}
	
}
